package com.example.mqttmanage.controller;


import com.example.mqttmanage.config.JwtUtil;
import com.example.mqttmanage.config.security.SecurityUtils;
import com.example.mqttmanage.domain.base.ResponseResult;
import com.example.mqttmanage.domain.user.User;
import com.example.mqttmanage.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private JwtUtil jwtUtil;

    // 登录接口
    @PostMapping("/login")
    public ResponseResult<Map<String, Object>> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");

        // 调用 Service 层进行登录验证
        ResponseResult<User> loginResult = userService.login(username, password);

        if (loginResult.getCode() == 200) { // 假设 200 是成功状态码
            User user = loginResult.getData();
            System.out.println(SecurityUtils.getCurrentUsername());
            String token = jwtUtil.generateToken(user.getUsername());
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", user);
            return ResponseResult.success(data);
        } else {
            // 登录失败，返回错误信息
            return ResponseResult.error(loginResult.getMsg());
        }
    }

    // 注册接口
    @PostMapping("/register")
    public ResponseResult<String> register(@RequestBody User user) {
        // 调用 Service 层进行用户注册
        ResponseResult<String> registerResult = userService.register(user);

        if (registerResult.getCode() == 200) { // 假设 200 是成功状态码
            return ResponseResult.success("注册成功");
        } else {
            // 注册失败，返回错误信息
            return ResponseResult.error(registerResult.getMsg());
        }
    }
}